<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\RongCloud;
use Hyperf\DbConnection\Model\Model;
/**
 * 用户账号
 */
class User extends Model
{
    /**
     * 用户表
     */
    protected $table = 'user';

    /**
     * 用户状态
     */
    const STATUS_OK = 0;
    const STATUS_FREEZE = 1;
    const STATUS_CANCELLATTED = 2;
    const STATUS_FORBID = 3;
    const STATUS = [
        self::STATUS_OK => '正常',
        self::STATUS_FREEZE => '冻结',
        self::STATUS_CANCELLATTED => '已注销',
        self::STATUS_FORBID => '禁言'
    ];

    /**
     * 注册系统
     */
    const PLATFORM_IOS = 1;
    const PLATFORM_ANDROID = 2;
    const PLATFORM = [
        self::PLATFORM_IOS => 'IOS',
        self::PLATFORM_ANDROID => '安卓',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_name', 'phone', 'version', 'device_id', 'client_ip', 'platform', 'android_market', 'device', 'pwd', "im_account", "im_token", "channel", "app_id", "cur_channel", "status","oaid","oaid_md5","imei"
    ];

    public function userProfile()
    {
        return $this->hasOne(UserProfile::class, 'user_id');
    }

    /**
     * 查找单个用户
     */
    static function getUser($userId = 0)
    {
        return self::find($userId);
    }

    /**
     * 创建账号
     */
    static function createAccount($data = [])
    {
        return self::create([
            'user_name' => $data['phone'] ?? '',
            'pwd' => $data['pwd'] ?? '',
            'phone' => $data['phone'] ?? '',
            'version' => $data['version'] ?? '1.0.1',
            'device_id' => $data['device_id'] ?? '',
            'device' => $data['device'] ?? '',
            'client_ip' => $data['client_ip'] ?? '',
            'platform' => $data['platform'] ?? 2,
            'android_market' => $data['android_market'] ?? '',
            'channel' => $data['channel'] ?? '',
            'cur_channel' => $data['channel'] ?? '',
            'app_id' => $data['app_id'] ?? 1,
            'oaid' => $data['oaid'] ?? '',
            'oaid_md5' => $data['oaid_md5'] ?? '',
            'imei' => $data['imei'] ?? ''
        ]);
    }

    /**
     * 根据手机号查找用户
     */
    static function checkPhone($phone = '')
    {
        if (!$phone) return null;
        $user = self::where('phone', $phone)->first();
        return $user ?: null;
    }

    /**
     * 更新手机号
     */
    static function updatePhone($userId = 0, $phone = '')
    {
        if (!$userId) return;
        return self::where('id', $userId)->limit(1)->update(['phone' => $phone]);
    }

    /**
     * 创建融云IM账号，并更新表字段token
     * @param $user
     * @return mixed
     */
    static function createRongIMAccount($userId = 0, $nickName = '', $avatar = '', $imAccount = '')
    {
        if (!$imAccount) {
            $prefix = env('RONG_ACCOUNT_PREFIX', 'moyu');
            $originKey = $prefix . '_' . $userId;
            $imAccount = $prefix == '' ? md5($originKey) : $prefix . '_' . md5($originKey);
        }
        //创建IM账号
        $result = (new RongCloud())->getToken($imAccount, $nickName ?: 'default_user', $avatar ?: '1');
        log_info("User==createRongIMAccount==Uid:{$userId}==Origin:{$originKey}==Ret:{$result}");
        $result = json_decode($result, true);
        if (isset($result['token']) && $result['token']) {
            $info = [
                'im_account' => $imAccount,
                'im_token' => $result['token']
            ];
            self::where('id', $userId)->limit(1)->update($info);
            return $info;
        }
        return null;
    }

    /**
     * 是否需要修改融云账号
     */
    static function needChangeImAccount($imAccount = '')
    {
        $prefix = env('RONG_ACCOUNT_PREFIX', '');
        if ($prefix && $prefix != explode('_', $imAccount)[0]) {
            log_info(__CLASS__ . "==needChangeImAccount==Prefix:{$prefix}==Account:{$imAccount}");
            return true;
        }
        return false;
    }

    /**
     * 修改IM账号昵称
     * @param string $account
     * @param string $nickname
     * @return array|mixed|string
     */
    static function updateIMInfo($account = '', $nickname = '', $avatar = '')
    {
        if (!$account || !$nickname) return false;
        $ret = (new RongCloud())->userRefresh($account, $nickname, $avatar ?: '1');
        $logArr = ["User", "updateImNickname", $account, $nickname, json_encode($ret)];
        log_info(implode('==', $logArr));
        return $ret;
    }

    /**
     * 根据用户ID获取IM账号
     */
    static function getImAccounts($userIds = [], $validStatus = self::STATUS_OK)
    {
        if (!$userIds) return [];
        if (!is_array($userIds)) $userIds = [$userIds];
        $where = [];
        $validStatus >= 0 && $where[] = ['status', self::STATUS_OK];
        return self::where($where)->whereIn('id', $userIds)->pluck('im_account', 'id')->toArray();
    }

    /**
     * 根据IM账号获取用户ID
     */
    static function getUserIdByIm($imAccounts = [], $dataType = 'kv')
    {
        if (!$imAccounts) return [];
        if (!is_array($imAccounts)) $imAccounts = [$imAccounts];
        switch ($dataType) {
            case 'kv':
                return self::whereIn('im_account', $imAccounts)->pluck('id', 'im_account')->toArray();
            case 'im_kv':
                return self::whereIn('im_account', $imAccounts)->pluck('im_account', 'id')->toArray();
            default:
                return self::whereIn('im_account', $imAccounts)->pluck('id')->toArray();
        }
        return [];
    }

    /**
     * 获取指定版本以下的老用户ID
     */
    static function getOldIds($appVersion = '1.0.1')
    {
        return self::where([['version', '<', $appVersion]])->pluck('id')->toArray();
    }

    /**
     * 官方账号ID
     */
    static function getOfficialIds()
    {
        $where = [
            ['official', 1],
            ['status', self::STATUS_OK]
        ];
        return self::where($where)->pluck('id')->toArray();
    }

    /**
     * 注册用户
     */
    static function getRegUsers($startTime = '', $endTime = '', $type = 'count', $channel = '', $version = '')
    {
        $where = [];
        if ($startTime) $where[] = ['created_at', '>=', $startTime];
        if ($endTime) $where[] = ['created_at', '<', $endTime];
        if ($channel) $where[] = ['channel', $channel];
        if ($version) $where[] = ['version', $version];
        if ($type == 'count') return self::where($where)->count();
        else return self::where($where)->pluck('id')->toArray();
    }

    /**
     * 检测用户当前版本
     */
    static function checkVersion($userId = 0)
    {
        if (!$userId) return '';
        if (is_array($userId)) {
            return self::whereIn('id', $userId)->pluck('version', 'id')->toArray();
        }
        $info = self::getUser($userId);
        return $info ? $info->version : '1.0';
    }

    /**
     * 是否官方小助手
     */
    static function checkOfficial($userId = 0)
    {
        $offcialId = check_dev_env() ? [174] : config('busi.kefu_uid');
        if (!is_array($userId)) return in_array($userId, $offcialId);
        foreach ($userId as $uid) if (in_array($uid, $offcialId)) return true;
        return false;
    }

    /**
     * 注销账号
     */
    static function cancelAccount($userId = 0)
    {
        //第三方解除绑定
        SocialAccount::where('user_id', $userId)->limit(1)->delete();
        //更新手机号
        $record = User::find($userId);
        if (
            !$record
            || strpos($record->phone, '-X') !== false
            || $record->status == self::STATUS_CANCELLATTED
        ) return false;
        $upInfo = [
            'phone' => $record->phone ? $record->phone . '-X' : '',
            'user_name' => $record->user_name ? $record->user_name . '-X' : '',
            'status' => self::STATUS_CANCELLATTED
        ];
        return $record->update($upInfo);
    }

    /**
     * 设备ID注册数
     */
    static function checkDeviceNum($deviceId = '', $appId = 1)
    {
        $where = [
            'device_id' => $deviceId,
            'app_id' => $appId,
        ];
        return !$deviceId ? 0 : self::where($where)->count();
    }

    /**
     * IP注册数
     */
    static function checkClientIpNum($clientIp = '', $appId = 1)
    {
        $where = [
            'client_ip' => $clientIp,
            'app_id' => $appId,
        ];
        return !$clientIp ? 0 : self::where($where)->count();
    }

    /**
     * 检测对应的版本（按马甲包）是否高于条件设置
     */
    static function checkUserValidVersion($userId = 0, $versionInfo = [])
    {
        $user = self::getUser($userId);
        return $versionInfo[$user->app_id] <= $user->version;
    }

    /**
     * 检测对应的版本（按马甲包）是否高于条件设置
     */
    static function checkValidVersion($version = '', $appId = 1, $versionInfo = [])
    {
        if (isset($versionInfo[0])) return $versionInfo[0] <= $version;
        return !isset($versionInfo[$appId]) ? true : $versionInfo[$appId] <= $version;
    }

    /**
     * 判断用户是否是指美颜版本
     */
    static function checkFaceSupport($userId, $user = null)
    {
        !$user && $user = User::getUser($userId);
        return User::checkValidVersion($user->version, $user->app_id, [1 => '1.0.0', 2 => '1.0.0']) ? 1 : 0;
    }

    /**
     * 白名单用户检测
     */
    static function checkWhite($userId = 0)
    {
        $user = self::getUser($userId);
        $phone = $user->phone;
        if ($phone) {
            $range = ['11811110001', '11811119999'];
            if ($phone <= $range[1] && $phone >= $range[0]) return true;
            $range = ['14000000001', '14000000700'];
            if ($phone <= $range[1] && $phone >= $range[0]) return true;
        }
        $validUids = explode(',', env('WHITE_UID', ''));
        if (in_array($userId, $validUids)) return true;
        return false;
    }

    /**
     * 是否超管
     */
    static function isSuperAdmin($userId = 0)
    {
        $superAdmin = (new SuperAdmin())->getSuperAdminUserIds();

        return in_array($userId, $superAdmin) ? 1 : 0;
    }

    /**
     * 判断此用户是否有绑定过邀请人
     * @param int $userId
     * @param string $deviceId
     * @param string $time
     */
    static function checkByTimeInvite($deviceId = '',$time = '')
    {
        $time = empty($time) ? date('Y-m-d H:i:s',strtotime("-30 day")) : $time;
        $uids = self::where('device_id',$deviceId)->where('created_at','>',$time)->pluck('id')->toArray();
        if(UserProfile::whereIn('user_id',$uids)->where('invite_code','<>','')->exists()){
            return true;
        }
        return false;
    }

    /**
     * 获取指定用户中已被注销和冻结的用户
     * @param array $userIds
     */
    static function getLogout($userIds = [])
    {
        if(empty($userIds)) return [];
        $uids = self::where('status',2)->whereIn('id',$userIds)->pluck('id')->toArray();
        return $uids;
    }
}
